/**
 * 换脸服务 - 封装AI换脸相关API
 */

// 导入配置文件
import config from '@/config/app.js'

// 后端API基础URL
const BASE_URL = config.AI_HTTP_REQUEST_URL;

/**
 * 单张图片换脸
 * @param {string} userImageUrl - 用户图片URL
 * @param {string} modelId - 素材ID
 * @param {Object} options - 可选配置
 * @returns {Promise<Object>} 换脸结果
 */
export const swapFace = async (userImageUrl, modelId, options = {}) => {
  try {
    if (!userImageUrl || !modelId) {
      throw new Error('用户图片URL和素材ID不能为空');
    }

    uni.showLoading({
      title: '正在换脸中...',
      mask: true
    });

    const requestData = {
      source_image: userImageUrl,
      model_id: modelId,
      ...options
    };
    
    console.log('换脸请求数据:', requestData);
    
    const [error, result] = await uni.request({
      url: `${BASE_URL}/faceswap/swap`,
      method: 'POST',
      data: requestData,
      header: {
        'Content-Type': 'application/json'
      },
      timeout: 60000 // 60秒超时
    });

    console.log('换脸接口响应:', [error, result]);
    console.log('错误信息:', error);
    console.log('响应状态码:', result ? result.statusCode : 'undefined');
    console.log('响应数据:', result ? result.data : 'undefined');

    uni.hideLoading();

    // 检查是否有错误
    if (error) {
      console.log('请求错误:', error);
      throw new Error(error.errMsg || '网络请求失败');
    }

    console.log('检查响应条件:');
    console.log('- statusCode:', result ? result.statusCode : 'undefined');
    console.log('- result.data:', result ? result.data : 'undefined');
    console.log('- result.data.code:', result && result.data ? result.data.code : 'undefined');
    
    if (result && result.statusCode === 200 && result.data && result.data.code === 200) {
      console.log('换脸成功，返回数据:', result.data.data);
      
      uni.showToast({
        title: '换脸成功',
        icon: 'success',
        duration: 2000
      });

      return {
        success: true,
        data: result.data.data,
        message: result.data.message || '换脸成功'
      };
    } else {
      console.log('换脸失败，响应数据:', result ? result.data : 'undefined');
      const errorMessage = result && result.data && result.data.message ? result.data.message : '换脸失败';
      throw new Error(errorMessage);
    }

  } catch (error) {
    uni.hideLoading();
    console.error('换脸失败:', error);

    uni.showToast({
      title: error.message || '换脸失败',
      icon: 'error',
      duration: 3000
    });

    return {
      success: false,
      error: error.message
    };
  }
};



/**
 * 上传图片并换脸（一体化处理）
 * @param {string} filePath - 本地文件路径
 * @param {string} modelId - 素材ID
 * @param {Object} options - 可选配置
 * @returns {Promise<Object>} 换脸结果
 */
export const uploadAndSwapFace = async (filePath, modelId, options = {}) => {
  try {
    if (!filePath || !modelId) {
      throw new Error('文件路径和素材ID不能为空');
    }

    uni.showLoading({
      title: '正在上传并换脸中...',
      mask: true
    });

    const result = await uni.uploadFile({
      url: `${BASE_URL}/faceswap/upload-and-swap`,
      filePath: filePath,
      name: 'source_image',
      formData: {
        model_id: modelId,
        ...options
      },
      header: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 120000 // 120秒超时
    });

    uni.hideLoading();

    if (result.statusCode === 200) {
      const responseData = JSON.parse(result.data);
      
      if (responseData.code === 200) {
        uni.showToast({
          title: '换脸成功',
          icon: 'success',
          duration: 2000
        });

        return {
          success: true,
          data: responseData.data,
          message: responseData.message
        };
      } else {
        throw new Error(responseData.message || '换脸失败');
      }
    } else {
      throw new Error(`HTTP错误: ${result.statusCode}`);
    }

  } catch (error) {
    uni.hideLoading();
    console.error('上传并换脸失败:', error);

    uni.showToast({
      title: error.message || '换脸失败',
      icon: 'error',
      duration: 3000
    });

    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 获取换脸任务状态
 * @param {string} taskId - 任务ID
 * @returns {Promise<Object>} 任务状态
 */
export const getSwapTaskStatus = async (taskId) => {
  try {
    if (!taskId) {
      throw new Error('任务ID不能为空');
    }

    const [error, result] = await uni.request({
      url: `${BASE_URL}/faceswap/task/status`,
      method: 'GET',
      data: {
        taskId: taskId
      },
      header: {
        'Content-Type': 'application/json'
      }
    });

    if (error) {
      throw new Error(error.errMsg || '网络请求失败');
    }

    if (result && result.statusCode === 200 && result.data && result.data.code === 200) {
      return {
        success: true,
        data: result.data.data
      };
    } else {
      const errorMessage = result && result.data && result.data.message ? result.data.message : '获取任务状态失败';
      throw new Error(errorMessage);
    }

  } catch (error) {
    console.error('获取任务状态失败:', error);

    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 获取换脸结果
 * @param {string} taskId - 任务ID
 * @returns {Promise<Object>} 换脸结果
 */
export const getSwapResult = async (taskId) => {
  try {
    if (!taskId) {
      throw new Error('任务ID不能为空');
    }

    const [error, result] = await uni.request({
      url: `${BASE_URL}/faceswap/result`,
      method: 'GET',
      data: {
        taskId: taskId
      },
      header: {
        'Content-Type': 'application/json'
      }
    });

    if (error) {
      throw new Error(error.errMsg || '网络请求失败');
    }

    if (result && result.statusCode === 200 && result.data && result.data.code === 200) {
      return {
        success: true,
        data: result.data.data
      };
    } else {
      const errorMessage = result && result.data && result.data.message ? result.data.message : '获取换脸结果失败';
      throw new Error(errorMessage);
    }

  } catch (error) {
    console.error('获取换脸结果失败:', error);

    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 验证图片URL
 * @param {string} imageUrl - 图片URL
 * @returns {Promise<Object>} 验证结果
 */
export const validateImageUrl = async (imageUrl) => {
  try {
    if (!imageUrl) {
      throw new Error('图片URL不能为空');
    }

    const [error, result] = await uni.request({
      url: `${BASE_URL}/faceswap/validate-url`,
      method: 'POST',
      data: {
        image_url: imageUrl
      },
      header: {
        'Content-Type': 'application/json'
      }
    });

    if (error) {
      throw new Error(error.errMsg || '网络请求失败');
    }

    if (result && result.statusCode === 200 && result.data && result.data.code === 200) {
      return {
        success: true,
        data: result.data.data
      };
    } else {
      const errorMessage = result && result.data && result.data.message ? result.data.message : '验证图片URL失败';
      throw new Error(errorMessage);
    }

  } catch (error) {
    console.error('验证图片URL失败:', error);

    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 获取图片信息
 * @param {string} imageUrl - 图片URL
 * @returns {Promise<Object>} 图片信息
 */
export const getImageInfo = async (imageUrl) => {
  try {
    if (!imageUrl) {
      throw new Error('图片URL不能为空');
    }

    const [error, result] = await uni.request({
      url: `${BASE_URL}/faceswap/image/info`,
      method: 'POST',
      data: {
        image_url: imageUrl
      },
      header: {
        'Content-Type': 'application/json'
      }
    });

    if (error) {
      throw new Error(error.errMsg || '网络请求失败');
    }

    if (result && result.statusCode === 200 && result.data && result.data.code === 200) {
      return {
        success: true,
        data: result.data.data
      };
    } else {
      const errorMessage = result && result.data && result.data.message ? result.data.message : '获取图片信息失败';
      throw new Error(errorMessage);
    }

  } catch (error) {
    console.error('获取图片信息失败:', error);

    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 带重试的换脸操作
 * @param {Function} swapFunction - 换脸函数
 * @param {Object} params - 换脸参数
 * @param {number} maxRetries - 最大重试次数
 * @returns {Promise<Object>} 换脸结果
 */
export const swapFaceWithRetry = async (swapFunction, params, maxRetries = 3) => {
  let lastError = null;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      console.log(`换脸尝试 ${attempt}/${maxRetries}`);
      
      const result = await swapFunction(...params);
      
      if (result.success) {
        return result;
      } else {
        lastError = result.error;
        
        // 如果不是最后一次尝试，等待后重试
        if (attempt < maxRetries) {
          await new Promise(resolve => setTimeout(resolve, 2000 * attempt)); // 递增等待时间
        }
      }
    } catch (error) {
      lastError = error.message;
      
      if (attempt < maxRetries) {
        await new Promise(resolve => setTimeout(resolve, 2000 * attempt));
      }
    }
  }

  // 所有重试都失败了
  uni.showToast({
    title: `换脸失败，已重试${maxRetries}次`,
    icon: 'error',
    duration: 3000
  });

  return {
    success: false,
    error: lastError
  };
}; 